<template>
  <div class="passwordLogin">
    <div class="icon">
      <van-icon name="arrow-left" @click="$router.go(-1)" size="20" />
    </div>
    <h3>手机号密码登录</h3>
    <div class="login-input">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="userphone"
            name="手机号"
            label="+86"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

const { $request } = getCurrentInstance().appContext.config.globalProperties;
const userphone = ref("");
const password = ref("");
const router = useRouter();
const route = useRoute();

// const token = ref(localStorage.getItem("access_token") || undefined);
const onSubmit = (values) => {
  console.log("submit", values);
  axios
    .post(
      `/apixt/uc/oauth/token?scope=all&grant_type=phone_pwd&phone_num=${userphone.value}&password=${password.value}`,
      "POST",
      {
        headers: {
          Authorization: "Basic dXNlci1jbGllbnQ6dXNlci1zZWNyZXQtODg4OA==",
          // "x-xt-client-info": "platform=h5;version=2.7.8",
        },
      }
    )
    .then((data) => {
      console.log(data);
      if (data.status !== 200) {
        alert(data.response.data.error_description);
        return;
      }
      // access_token = data.data.access_token;
      // token_type = data.data.token_type;
      localStorage.setItem("token", `${data.data.token_type} ${data.data.access_token}`);
      const destPath = route.query.redirect;
      if (destPath) router.replace(destPath);
      else router.replace("/");
    });
  
};
</script>

<style lang="less" scoped>
.passwordLogin {
  padding: 20px 30px 50px;
  box-sizing: border-box;
  h3 {
    text-align: center;
    font-size: 20px;
    font-weight: normal;
    margin-bottom: 30px;
  }
}
</style>